<script lang="ts" setup>
import { ref, reactive, onMounted } from 'vue';
import { ElMessage, ElMessageBox, FormInstance, FormRules, genFileId, UploadFile, UploadFiles, UploadInstance, UploadProps, UploadRawFile } from 'element-plus';
import useStore from '@/store';
import { props } from './form';
import lens from '@/api/lens';
import { WindowType } from '@/types/global/window';
defineOptions({ name: 'StockInventoryOrderForm' });
const _props = defineProps(props);
const save = async () => {
  if (!ruleFormRef.value) return;
  await ruleFormRef.value.validate((valid, fields) => {
    if (valid) {
      if (!form.details || form.details.length <= 0) {
        ElMessage.success('请添加盘点镜种!');
        return;
      }
      window.$api.stockInventoryOrder.save(form).then(res => {
        ElMessage.success('保存成功!');
        useStore.window.windowRemove(_props.window?.name);
        if (_props.window?.callBack) _props.window?.callBack();
      });
    }
  });
};
const tableRef = ref(null);
const selectLens = ref(null);
const lensId = ref(null);
const warehouses = ref(null);
const disableWarehouse = ref(false);
const lenses = ref(null);
const loading = ref(false);

const ruleFormRef = ref<FormInstance>();
const form = reactive({
  id: null,
  number: null,
  warehouseId: null,
  remark: null,
  details: null,
});
const rules = reactive<FormRules>({
  warehouseId: [{ required: true, message: '请选择仓库', trigger: 'change' }],
});
/** 加载基础数据,字典等 */
const init = async () => {
  await window.$api.warehouse.getWarehouses().then(res => {
    warehouses.value = res.data;
  });
};
const detail = async () => {
  await window.$api.stockInventoryOrder.detail(_props.window.params.id).then(res => {
    form.id = res.data.id;
    form.number = res.data.number;
    form.warehouseId = res.data.warehouseId;
    form.details = res.data.details;
    form.remark = res.data.remark;
    disableWarehouse.value = true;
  });
  await getLenses();
};
const warehouseChange = val => {
  form.warehouseId = val;
  getLenses();
};

const getLenses = async () => {
  window.$api.lens.getStockLenses(form.warehouseId).then(res => {
    lenses.value = res.data;
  });
};
const addInventoryLens = () => {
  if (!selectLens.value) {
    ElMessage.error('请选择镜种!');
    return;
  }
  if (!form.details) {
    form.details = [];
  }
  if (!disableWarehouse.value) disableWarehouse.value = true;
  if (form.details.find(item => item.lensId == selectLens.value.id)) {
    ElMessage.error('镜种已存在!');
    return;
  }
  let detail = {
    lensId: selectLens.value.id,
    lensCode: selectLens.value.factoryLensCode,
    lensName: selectLens.value.factoryLensName,
    qty: 0,
    xyTable: null,
  };
  form.details.push(detail);
};
const lensChange = val => {
  selectLens.value = lenses.value.find(item => item.id == val);
};
const showImport = val => {
  let orderDetail = form.details.find(item => item.lensId == val);
  let w = warehouses.value.find(item => item.id == form.warehouseId);
  const window: WindowType = {
    name: 'StockInventoryOrderFormImportForm',
    component: 'StockInventoryOrderFormImportForm',
    label: '库存盘点导入（' + orderDetail.lensCode + '）',
    icon: 'edit',
    width: 800,
    height: 500,
    params: { warehouse: w, detail: orderDetail },
    callBack: (val, xyTable) => setXYTable(val, xyTable),
  };
  useStore.window.windowAdd(window);
};
const remove = val => {
  let orderDetail = form.details.find(item => item.lensId == val);
  ElMessageBox.confirm('是否删除' + orderDetail.lensCode, '提示', {
    confirmButtonText: '确认',
    cancelButtonText: '取消',
    type: 'warning',
  })
    .then(() => {
      form.details = form.details.filter(item => item.lensId != val);
      if (form.details.length <= 0) disableWarehouse.value = false;
    })
    .catch(() => {});
};
const setXYTable = (val, xyTable) => {
  let orderDetail = form.details.find(item => item.lensId == val);
  orderDetail.xyTable = xyTable;
  orderDetail.qty = xyTable[xyTable.length - 1].total;
};
onMounted(() => {
  init();
  if (_props.window.params) {
    if (_props.window.params.id) {
      detail();
    }
  }
});
</script>

<template>
  <windows-window :window="window" v-loading="loadingDownLoad">
    <template #button>
      <windows-button-group size="18">
        <windows-button icon="fluent-save-28-regular" @click="save" split></windows-button>
      </windows-button-group>
    </template>
    <el-form ref="ruleFormRef" :model="form" :rules="rules" label-width="80px" class="demo-ruleForm" size="default" status-icon>
      <el-row>
        <el-col :span="24">
          <el-form-item label="盘点单号" prop="number">
            <el-input disabled v-model="form.number" placeholder="" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-form-item label="备注" prop="remark">
            <el-input v-model="form.remark" type="textarea" />
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="24">
          <el-row>
            <el-col :span="10">
              <el-form-item label="仓库" prop="warehouseId">
                <el-select clearable filterable v-model="form.warehouseId" @change="warehouseChange" placeholder="请选择仓库" :disabled="disableWarehouse">
                  <el-option v-for="item in warehouses" :key="item.id" :label="item.name" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="10">
              <el-form-item label="镜种" prop="lensId">
                <el-select clearable filterable v-model="lensId" placeholder="请选择镜种" @change="lensChange">
                  <el-option v-for="item in lenses" :key="item.id" :label="item.factoryLensCode" :value="item.id" />
                </el-select>
              </el-form-item>
            </el-col>
            <el-col :span="4" style="text-align: right">
              <el-button type="success" icon="CirclePlus" @click="addInventoryLens">新增</el-button>
            </el-col>
          </el-row>
          <el-table ref="tableRef" :data="form.details" style="width: 100%" highlight-current-row v-loading="loading">
            <el-table-column type="index" width="80" label="序号" align="center" />
            <el-table-column prop="lensCode" label="盘点镜种" align="center" minWidth="150" show-overflow-tooltip></el-table-column>
            <el-table-column prop="lensName" label="镜种名称" align="center" minWidth="200" show-overflow-tooltip></el-table-column>
            <el-table-column prop="qty" label="盘点总数" align="center" minWidth="80"></el-table-column>
            <!-- <el-table-column prop="inQty" label="盘盈数量" align="center" width="80"></el-table-column>
            <el-table-column prop="outQty" label="盘亏数量" align="center" width="80"></el-table-column> -->
            <el-table-column label="操作" align="center">
              <template #default="scope">
                <el-link type="primary" :underline="false" style="margin-right: 5px" @click="showImport(scope.row.lensId)">导入</el-link>
                <el-link type="primary" :underline="false" @click="remove(scope.row.lensId)">移除</el-link>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-form>
  </windows-window>
</template>

<style scoped lang="scss">
#edit {
  height: 100%;
}
.el-form {
  margin: 30px 20px;
  .el-upload-dragger {
    padding: 0;
  }
}
.custom-node {
  display: flex;
  align-items: center;
  span {
    margin-left: 5px;
  }
}
.select-icon {
  display: flex;
  align-items: baseline;
  flex-wrap: wrap;
  border: 1px solid #dcdfe6;
  border-radius: 5px;
  margin-top: 5px;
  background: #fff;
  width: 100%;
  height: 200px;
  overflow: auto;
  .el-image {
    margin: 10px;
    cursor: pointer;
    border-radius: 5px;
    padding: 5px;
    &:hover,
    &.active {
      background: #dcdfe6;
    }
  }
}
</style>
